package com.orange.core.security.token;

import com.orange.core.security.detail.UserDetail;
import lombok.Getter;
import lombok.Setter;
import org.springframework.security.core.Authentication;

import java.io.Serializable;
import java.util.ArrayList;

@Getter
@Setter
public class WxPersistenceToken implements Serializable {

    private UserDetail principal;
    private Boolean authenticated;

    public static WxPersistenceToken of(WxAuthenticationToken token) {
        if (token.getPrincipal() instanceof UserDetail principal) {
            WxPersistenceToken persistenceToken = new WxPersistenceToken();
            UserDetail persistencePrincipal = new UserDetail(principal.getId(), principal.getUsername(), new ArrayList<>())
                    .setUser(principal.getUser()).setToken(principal.getToken());
            persistenceToken.setPrincipal(persistencePrincipal);
            persistenceToken.setAuthenticated(token.isAuthenticated());
            return persistenceToken;
        } else {
            throw new RuntimeException("token未认证");
        }
    }

    public Authentication toAuthenticationToken() {
        return new WxAuthenticationToken(principal, new ArrayList<>());
    }
}
